import React, { useState, useEffect, useCallback } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { Modal } from 'antd';
import LinkButton from '../link-button';
import menuList from '../../config/menuConfig';
import { formateDate } from '../../utils/dateUtils';
import memoryUtils from '../../utils/memoryUtils';
import storageUtils from '../../utils/storageUtils';
import './index.less';

const Header = () => {
  const [currentTime, setCurrentTime] = useState(formateDate(Date.now()));
  const [title, setTitle] = useState('');

  const location = useLocation();
  const navigate = useNavigate();

  useEffect(() => {
    const timerId = setInterval(() => {
      setCurrentTime(formateDate(Date.now()));
    }, 1000);
    return () => clearInterval(timerId);
  }, []);

  const getTitle = useCallback(() => {
    let effectivePath = location.pathname.replace('/admin/', '');  //接受两个参数，第一个参数是要被替换的字符串，第二个参数是用于替换的新字符串
    if (!effectivePath || effectivePath === '/admin') {
      effectivePath = 'home';
    }

    const findTitle = (menuItems) => {
      for (const item of menuItems) {
        if (item.children) {
          const childTitle = findTitle(item.children);
          if (childTitle) return childTitle;

          if (effectivePath.startsWith(`${item.key}/`)) {
            return item.title;
          }
        } else {
          if (item.key === effectivePath || effectivePath.startsWith(`${item.key}/`)) {
            return item.title;
          }
        }
      }
      return null;
    };

    return findTitle(menuList) || '未知标题';
  }, [location.pathname]);

  useEffect(() => {
    setTitle(getTitle());
  }, [getTitle]);

  const logout = () => {
    Modal.confirm({
      content: '确定退出吗?',
      onOk: () => {
        storageUtils.removeUser();
        memoryUtils.user = {};
        navigate('/login', { replace: true });
      }
    });
  };

  return (
    <div className="header">
      <div className="header-top">
        <span>欢迎, {memoryUtils.user.username}</span>
        <LinkButton onClick={logout}>退出</LinkButton>
      </div>
      <div className="header-bottom">
        <div className="header-bottom-left">{title}</div>
        <div className="header-bottom-right">
          <span>{currentTime}</span>
        </div>
      </div>
    </div>
  );
};

export default Header;
